﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace Upload2Flickr
{
    public partial class Main : Form
    {
        string Folder = null;
        bool IsPublic = false;

        public Main(string folder = null, bool isPublic = false)
        {
            InitializeComponent();
            Folder = folder;
            IsPublic = isPublic;
        }

        private void GoButton_Click(object sender, EventArgs e)
        {
            DialogResult res = System.Windows.Forms.DialogResult.OK;
            while ((FlickrManager.OAuthToken == null || FlickrManager.OAuthToken.Token == null) && res != DialogResult.Cancel)
            {
                AuthForm f = new AuthForm();
                res = f.ShowDialog();
            }
            RefreshUserLabel();
            if (!(FlickrManager.OAuthToken == null || FlickrManager.OAuthToken.Token == null))
            {
                RefreshButtons(false);
                backgroundWorker1.RunWorkerAsync();
            }
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                var fl = FlickrManager.GetAuthInstance();
                string folder = folderTextBox.Text;
                if (folder == null)
                    return;
                if (folder.EndsWith("\\"))
                    folder = folder.Remove(folder.Length - 1, 1);
                string folder_success = folderTextBox.Text + "_success";
                string folder_failed = folderTextBox.Text + "_failed";

                string[] files = Directory.GetFiles(folderTextBox.Text, "*.*", SearchOption.AllDirectories);
                int i = 0;
                foreach (string f in files)
                {
                    if (e.Cancel)
                        return;
                    try
                    {
                        string photoId = fl.UploadPicture(f, null, null, null, publicCheckBox.Checked, false, false);
                        string successPath = f.Replace(folder, folder_success);
                        if (!CreatePath(successPath, true))
                            return;
                        File.Move(f, successPath);
                    }
                    catch
                    {
                        string failedPath = f.Replace(folder, folder_failed);
                        try
                        {
                            if (!CreatePath(failedPath, true))
                                return;
                            File.Move(f, failedPath);
                        }
                        catch
                        {
                            MessageBox.Show("Failed to move file to " + failedPath);
                            return;
                        }
                    }
                    i++;
                    backgroundWorker1.ReportProgress((int)(((double)i / (double)files.Length) * 100));
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
        }

        private bool CreatePath(string path, bool file)
        {
            DirectoryInfo di = null;
            try
            {
                if (file)
                {
                    FileInfo fi = new FileInfo(path);
                    di = fi.Directory;
                }
                else
                {
                    di = new DirectoryInfo(path);
                }
                if (!di.Exists)
                {
                    DirectoryInfo p = di.Parent;
                    if (CreatePath(p.FullName, false))
                    {
                        Directory.CreateDirectory(di.FullName);
                        //p.CreateSubdirectory(di.FullName);
                    }
                    else
                    {
                        return false;
                    }
                }
                return true;
            }
            catch
            {
                string dir = path;
                if (di != null)
                    dir = di.FullName;
                MessageBox.Show("Creating folder " + dir + " failed");
                return false;
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            RefreshButtons(true);

            if (Folder == null)
            {
                MessageBox.Show("Upload completed");
            }
            else
            {
                this.Close();
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            if (Properties.Settings.Default.LastFolder == null)
            {
                folderTextBox.Text = System.Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);
            }
            else
            {
                folderTextBox.Text = Properties.Settings.Default.LastFolder;
            }
            RefreshUserLabel();
            if (Folder != null)
            {
                folderTextBox.Text = Folder;
                publicCheckBox.Checked = IsPublic;
                GoButton_Click(null, null);
            }
        }

        private void StopButton_Click(object sender, EventArgs e)
        {
            RefreshButtons(true);

            backgroundWorker1.CancelAsync();

            Folder = null;

            MessageBox.Show("Upload stopped");
        }

        private void RefreshButtons(bool enabled)
        {
            GoButton.Enabled = enabled;
            publicCheckBox.Enabled = enabled;
            StopButton.Enabled = !enabled;
            SetUserButton.Enabled = enabled;
            folderTextBox.Enabled = enabled;
            FolderButton.Enabled = enabled;
        }

        private void FolderButton_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = folderTextBox.Text;
            if (folderBrowserDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                folderTextBox.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void folderTextBox_TextChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.LastFolder = folderTextBox.Text;
            Properties.Settings.Default.Save();
        }

        private void SetUserButton_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            AuthForm f = new AuthForm();
            f.ShowDialog();
            RefreshUserLabel();
        }

        private void RefreshUserLabel()
        {
            if (FlickrManager.OAuthToken == null || FlickrManager.OAuthToken.Token == null)
            {
                SetUserButton.Text = "Not logged in";
            }
            else
            {
                SetUserButton.Text = "Logged in as " + FlickrManager.OAuthToken.FullName;
            }
        }
    }
}
